package com.wuwei.elearning.utils;

import com.coremedia.iso.IsoFile;
import com.coremedia.iso.boxes.MovieHeaderBox;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Component
public class FileUtils {

    /**
     * 将 MultipartFile 转换为 File
     * @param multipartFile 上传的文件
     * @return File 对象
     */
    @SneakyThrows
    public static File convertMultipartFileToFile(MultipartFile multipartFile) {
        // 创建临时文件
        File tempFile = File.createTempFile("temp_", "_" + multipartFile.getOriginalFilename());
        // 将文件写入临时文件
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(multipartFile.getBytes());
        }
        // 程序结束时删除临时文件
        tempFile.deleteOnExit();
        return tempFile;
    }

    public static long extractVideoDuration(File tempFile) throws Exception {
        try (IsoFile isoFile = new IsoFile(tempFile.getAbsolutePath())) {
            MovieHeaderBox movieHeaderBox = isoFile.getMovieBox().getMovieHeaderBox();
            return movieHeaderBox.getDuration() / movieHeaderBox.getTimescale();
        }
    }
}
